<template>
  <div>
    <nav-bar class="nav-bar">
      <template v-slot:default>
        购物车(<span style="color: red">{{ $store.state.cartCount }}</span>)
      </template>
    </nav-bar>
    <div class="cart-box">
      <div class="cart-body">
        <van-checkbox-group ref="checkboxGroup" @change="groupChange" v-model="result">
          <van-swipe-cell :right-width="50"
          v-for="(item, index) in list" :key="index"
          >
            <div class="good-item">
              <!--选中购物车中商品的ID-->
              <van-checkbox :name="item.id" />
              <div class="good-img">
                <img :src="item.goods.cover_url" />
              </div>
              <div class="good-desc">
                <div class="good-title" style="font-size: 14px;">
                  <span>{{ item.goods.title }}</span>
                  <span>仅剩: {{ item.goods.stock }}</span>
                </div>
                <div class="good-btn">
                  <div class="price">
                    <small>￥</small>{{ item.goods.price + '.00'}}
                  </div>
                  <van-stepper
                    integer
                    :min="1"
                    :max="item.goods.stock"
                    :model-value="item.num"
                    :name="item.id"
                    async-change
                    @change="onChange"
                  />
                </div>
              </div>
            </div>
            <template #right>
              <van-button
                square
                icon="delete"
                type="danger"
                class="delete-button"
                @click="deleteGood(item.id)"
              />
            </template>
          </van-swipe-cell>
        </van-checkbox-group>
      </div>
      <van-submit-bar class="submit-all" :price="total*100" @submit="onSubmit" button-text="结算" >
        <van-checkbox v-model:checked="checkAll" @click="allCheck">全选</van-checkbox>
      </van-submit-bar>

      <!-- 购物车为 0 时 -->
      <div class="empty" v-if="!list.length">
        <img class="empty-cart" src="~assets/images/empty-car.png" alt="空购物车" />
        <div class="title">购物车空空如也</div>
        <van-button round color="#1baeae" type="primary" block @click="goTo">前往选购</van-button>
      </div>
    </div>
  </div>
</template>

<script >
import NavBar from "@/components/common/navbar/NavBar.vue";
import { ref, reactive, toRefs, onMounted, computed, toRef, } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { Toast } from "vant";
import { getCart, checkedCart, modifyCart, deleteCartItem,} from "@/network/cart";

export default{
  name: 'shopCart',
  setup() {
    const router = useRouter()
    const store = useStore()
    // 购物车数据模型
    const state = reactive({
      list: [],
      // 购物车 id 数组
      result: [],
      checkAll: true

    })

    // 初始化购物车数据
    const init = async () =>{
      Toast.loading({message: '加载中...', forbidClick: true})
      // 发起请求
      const data = await getCart('include=goods')
      state.list = data.data
      state.result = data.data.filter(item => item.is_checked === 1 ).map(n => n.id)
      Toast.clear()
    }

    onMounted(()=>{
      init()
    })

    // 异步修改购物车数量
    const onChange = async (value, detail) => {
      Toast.loading({message: '修改中', forbidClick: true})
      const data = await modifyCart(detail.name, {num: value})
      // 把在 onMounted 中的 list 中的 num 值改为最新值
      state.list.forEach(item=>{
        if (item.id === detail.name) {
          item.num = value
        }
      })

      Toast.clear()
    }

    // 复选框改变处理
    const groupChange = (result)=>{
      if(result.length === state.list.length) {
        state.checkAll = true
      } else {
        state.checkAll = false
      }
      state.result = result
      // 发起请求，改变数据库中的商品选中状态
      checkedCart({cart_ids: result})
    }

    // 全选反选
    const allCheck = () =>{
      if(!state.checkAll) {
        state.result = state.list.map(item=>item.id)
        state.checkAll = true
      } else {
        state.result = []
        state.checkAll = true
      }
    }

    // 删除商品
    const deleteGood = async (id) => {
      const data = await deleteCartItem(id)
      init() //重新初始化
      store.dispatch('updateCart')  // 改变 vuex 中的状态数量
    }

    // 计算总价
    const total = computed(()=>{
      let sum = 0
      state.list.filter(item => state.result.includes(item.id))
      .forEach(item => {
        sum += parseFloat(item.goods.price) * parseInt(item.num)
      })
      return sum
    })

    // 结算，创建订单
    const onSubmit = () => {
      if (state.result.length === 0) {
        Toast.fail('至少选择一件商品')
      } else {
        router.push('/createorder')
      }
    }

    // 购物车为空时的 前往购物按钮
    const goTo = () =>{
      router.push('/home')
    }

    return {
      ...toRefs(state),
      goTo,
      onChange,
      groupChange,
      allCheck,
      deleteGood,
      onSubmit,
      total
    }
  },
  components:{
    NavBar
  }
}
</script>
<style lang="scss" scoped>
.cart-box {
  .cart-body {
    margin: 60px 0 100px 0;
    padding-left: 10px;
    .good-item {
      display: flex;
      .good-img {
        img {
          width: 100px;
          height: auto;
        }
      }
      .good-desc {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        flex: 1;
        padding: 20px;
        .good-title {
          display: flex;
          justify-content: space-between;
        }
        .good-btn {
          display: flex;
          justify-content: space-between;
          .price {
            font-size: 16px;
            color: red;
            line-height: 28px;
          }
          .van-icon-delete {
            font-size: 20px;
            margin-top: 4px;
          }
        }
      }
    }
    .delete-button {
      width: 50px;
      height: 100%;
    }
  }
  .empty {
    width: 50%;
    margin: 0 auto;
    text-align: center;
    margin-top: 200px;
    .empty-cart {
      width: 150px;
      margin-bottom: 20px;
    }
    .van-icon-smile-o {
      font-size: 50px;
    }
    .title {
      font-size: 16px;
      margin-bottom: 20px;
    }
  }
  .submit-all {
    margin-bottom: 53px;
    .van-checkbox {
      margin-left: 0px;
    }
    .van-submit-bar__text {
      margin-right: 10px;
    }
    .van-submit-bar__button {
      background: red;
    }
  }
  .van-checkbox__icon--checked .van-icon {
    background-color: red;
    border-color: red;
  }
}
</style>